package com.algorithm.code.queue;

/**
 * @description T这个队列的实现方式和我的方式有区别
 *
 * @program: sudy
 * @author: kukuxiahuni
 * @create: 2020-01-25 19:36
 **/
public class CycleArrayQueue<T> implements BaseQueue<T> {

    private int capacity;
    private int head = 0, tail = 0;
    private T[] queue;

    /**
    * @Description: 
    * @Param: 
    * @return: 
    * @Author: kukuxiahuni
    * @Date: 2020/1/25
    */
    public CycleArrayQueue(int capacity) {
        this.queue = (T[]) new Object[capacity];
        this.capacity = capacity;
    }

    @Override
    public T peek() {
        /**
         * 队列为空
         */
        if (tail == head) {
            return null;
        }
        return this.queue[head] ;
    }

    @Override
    public T poll() {
        if (tail == head) {
            return null;
        }

        T val = this.queue[head];
        this.queue[head] = null;
        head = (head + 1) % capacity;

        return val;
    }

    @Override
    public void push(T val) {

        /**
         * 如果队列空,则直接返回
         */
        if (isFull()) {
            return;
        }

        this.queue[tail] = val;
        tail = (tail + 1) % capacity;




    }

    /**
    * @Description: 如果队列满了,则表示 tail指针下一个就是head指针
    * @Param:
    * @return:
    * @Author: kukuxiahuni
    * @Date: 2020/1/25
    */
    private final boolean isFull() {
        return (tail + 1) % capacity == head;
    }
}
